package personal.lijun.skeleton.web.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import personal.lijun.skeleton.springcloud.common.data.ApiResultListSet;
import personal.lijun.skeleton.springcloud.common.data.ApiResultSet;
import personal.lijun.skeleton.web.Exception.CallRpcServiceException;
import personal.lijun.skeleton.web.feign.CalendarServiceFeign;
import personal.lijun.skeleton.web.feign.CalendarUser;
import personal.lijun.skeleton.web.feign.Role;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/16 17:43
 */
//@Component
public class CalendarUserAuthenticationProvider  implements AuthenticationProvider {

    private final CalendarServiceFeign calendarService;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public CalendarUserAuthenticationProvider(final CalendarServiceFeign calendarService,
    final PasswordEncoder passwordEncoder) {
        if (calendarService == null) {
            throw new IllegalArgumentException("calendarService cannot be null");
        }
        if (passwordEncoder == null) {
            throw new IllegalArgumentException("passwordEncoder cannot be null");
        }

        this.calendarService = calendarService;
        this.passwordEncoder = passwordEncoder;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String email = token.getName();
        CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
        if(user == null) {
            throw new UsernameNotFoundException("Invalid username/password");
        }
        // Database Password already encrypted:
        String password = user.getPassword();

        boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

        if(!passwordsMatch) {
            throw new BadCredentialsException("Invalid username/password");
        }
        Collection<? extends GrantedAuthority> authorities =createAuthorities(user.getId());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
        return usernamePasswordAuthenticationToken;
    }

    protected Collection<? extends GrantedAuthority> createAuthorities(Long userId){
        ApiResultListSet<Role> rolesList = calendarService.findUserRoles(userId);
        if(rolesList.getCode() != ApiResultSet.SUCCESS){
            throw new CallRpcServiceException(rolesList.toFullMessage());
        }

        Set<GrantedAuthority> grantedAuthoritySet = new HashSet<>();
        for(Role role : rolesList){
            grantedAuthoritySet.add(new SimpleGrantedAuthority(role.getName()));
        }
        return grantedAuthoritySet;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}
